﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HashMaster.Lib;
using System.Threading;
using System.IO;
using System.Net;
using System.Web;


namespace HashMaster.HashMonitor
{
    class Program
    {
        static List<Client> clients;
        static List<Task> tasks;
        //static List<Client> NotifyList = new List<Client>();
        const string ServiceUrl = @"http://localhost:1456/";
        const int DeadInterval = 300;

        static Dictionary<string, List<Client>> NotifyList = new Dictionary<string, List<Client>>();


        static void Main(string[] args)
        {
            NotifyList.Add("13520928515as", new List<Client>());
            NotifyList.Add("18623352787uf", new List<Client>());
            NotifyList.Add("13521163705ch", new List<Client>());
            NotifyList.Add("13906613487de", new List<Client>());
            NotifyList.Add("13810536612xy", new List<Client>());
            NotifyList.Add("15961619404df", new List<Client>());
            NotifyList.Add("13661517185qq", new List<Client>());
            NotifyList.Add("15900839454aa", new List<Client>());

            /// 文件监视 IMEI.INI
            FileSystemWatcher watcher = new FileSystemWatcher("c:\\imeis", "imei.ini");
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.EnableRaisingEvents = true;


            /// gtalk账号设置
            //////////xmpp = new XmppClientConnection("gmail.com");
            //////////xmpp.Password = "123456abc!";
            //////////xmpp.Username = "larvata.bot";
            //////////xmpp.ConnectServer = "talk.google.com";
            //////////xmpp.KeepAlive = true;
            //////////xmpp.Open();


            while (true)
            {


                //////////if (xmpp.XmppConnectionState!= XmppConnectionState.SessionStarted)
                //////////{
                //////////    ///循环保证gtalk登陆状态
                //////////    Console.WriteLine("close and open");
                //////////    xmpp.Close();
                //////////    Thread.Sleep(2000);
                //////////    xmpp.Open();
                //////////    Thread.Sleep(3000);

                //////////    continue;

                //////////}
                //////////else
                //////////{
                //Console.WriteLine("start check");
                ///获取客户端清单
                clients = ServiceUtility.GetAllClients(ServiceUrl);
                foreach (var c in clients)
                {
                    /// 客户端失控
                    if (DateTime.Now.Subtract(c.LastActive).TotalSeconds > DeadInterval)
                    {
                        ServiceUtility.DisableClient(c, ServiceUrl);
                        foreach (var item in NotifyList)
                        {
                            if (item.Key.Contains(c.ClientName.Substring(0, 2).ToLower()))
                            {
                                item.Value.Add(c);
                                break;
                            }
                        }
                        //c.ClientName
                    }
                }

                ///生成cod
                tasks = ServiceUtility.GetExtractableTasks(ServiceUrl);

                foreach (var t in tasks)
                {
                    File.WriteAllText("c:\\cods\\" + t.Imei + "_COD.txt", t.Result);
                    Console.WriteLine("输出" + t.Imei + "_COD.txt");
                    ServiceUtility.ModifyTask(ServiceUrl, t.Imei, extracted: true);
                }


                ///发送通知
                string errMessage = string.Empty;
                ////////////foreach (Client client in NotifyList)
                ////////////{
                ////////////    errMessage += client.ClientName + "\r\n";
                ////////////    ////////////////////NotifyList.Remove(client);
                ////////////}
                foreach (var item in NotifyList)
                {

                    if (item.Value.Count > 0)
                    {
                        string strTmp = string.Empty;
                        foreach (var c in item.Value)
                        {
                            strTmp += c.ClientName + "\r\n";

                        }
                        item.Value.Clear();
                        string strUrl = string.Format("http://lab.3haku.net/f/do?phone=15900839454&pwd=attack1984&to={0}&msg={1}&u=1", item.Key.Substring(0, 11), strTmp);
                        WebRequest request = HttpWebRequest.Create(strUrl);
                        try
                        {
                            WebResponse response = request.GetResponse();
                            StreamReader sr = new StreamReader(response.GetResponseStream());
                            if (!sr.ReadToEnd().Contains("<statu>success</statu>"))
                            {
                                errMessage += string.Format("发送短信失败：{0}\r\n", item.Key.Substring(0, 11));
                            }

                        }
                        catch (Exception ex)
                        {

                            errMessage += string.Format("发送短信出错：{0}\r\n", item.Key.Substring(0, 11));
                            errMessage += ex.Message;
                        }



                        errMessage += strTmp;
                    }
                }


                if (errMessage.Length > 0)
                {
                    errMessage = string.Format("{1}\r\n{0}\r\n以下主机未响应：\r\n{2}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), errMessage);
                    //xmpp.Send(new ags.Message("alzzlnewtype@gmail.com", ags.MessageType.chat, errMessage));
                    //xmpp.Send(new ags.Message("stcpub@gmail.com", ags.MessageType.chat, errMessage));

                    Console.WriteLine(errMessage);

                }

                Thread.Sleep(100000);
            }


            //}



        }



        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            //Console.WriteLine("changed");
            //throw new NotImplementedException();
            string rawImei;
            string rawSha;
            string memo;
            int count = 0;
            int err = 0;

            try
            {
                using (StreamReader reader = new StreamReader(new FileStream("c:\\imeis\\imei.ini", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    while (!reader.EndOfStream)
                    {
                        rawImei = reader.ReadLine();
                        if (rawImei.Length == 0) continue;
                        if (rawImei.Substring(0, 1) == "[" && rawImei.Substring(rawImei.Length - 1, 1) == "]")
                        {
                            rawImei = rawImei.Substring(1, rawImei.Length - 2);
                            rawSha = reader.ReadLine();
                            rawSha = rawSha.Substring(4);
                            memo = reader.ReadLine();

                            bool ret = ServiceUtility.AddNewTask(rawImei, rawSha, 5, ServiceUrl);

                            if (ret == true)
                            {
                                count++;
                            }
                            else
                            {
                                err++;
                            }
                        }
                    }
                    if (count > 0)
                    {
                        //xmpp.Send(new ags.Message("alzzlnewtype@gmail.com", ags.MessageType.chat, "新增 " + count.ToString() + "个任务，" + err.ToString() + " 个重复"));
                        //xmpp.Send(new ags.Message("stcpub@gmail.com", ags.MessageType.chat, "新增 " + count.ToString() + "个任务，" + err.ToString() + " 个重复"));
                        Console.WriteLine("新增 " + count.ToString() + "个任务，" + err.ToString() + " 个重复");
                    }

                }
            }
            catch (IOException ex)
            {
                Console.WriteLine("读取imeis.ini出错\r\n{0}",ex.Message);

            }



        }

    }
}
